﻿/**
 * background
 * ibio-develop
 */
(function(window){
var m_hBadge = 0;
var m_hSetBadgeText = 0;
var m_leftTime = 0;
var m_pauseCurrentTime = false;
var m_isGettingOffWork = false;
var m_data = getLocalData(KEY_HE_DATA) || {};

//legacy method
var oldData = getLocalData("_he_leave_data") || {};
if(oldData.username && oldData.password && !m_data.username && !m_data.password){
	m_data.username = oldData.username;
	m_data.password = oldData.password;
	setLocalData(m_data, KEY_HE_DATA);
}

//expose to popup
window.findSomedayData = findSomedayData;
window.isTheLatestData = isTheLatestData;
window.fetchLeaveData = fetchLeaveData;
window.fetchData = function(){
	m_data.pastTime = getPastTime();
	m_data.totalTime = DUTY_HOURS * 60 * 60 * 1000;
	m_data.leftTime = m_leftTime;
	setLocalData(m_data, KEY_HE_DATA);
	return m_data;
}
window.clearData = function(data){
	m_data = data;
	setLocalData(m_data, KEY_HE_DATA);
	trace("clear data", m_data);
}

chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
	switch(request.type){
		case "setData":
			m_data = getLocalData(request.key) || {};
			//merge
			_.each(request.value, function(value, key){m_data[key] = value});
			setLocalData(m_data, request.key);
			sendResponse && sendResponse();
			break;
		case "getData":
			sendResponse && sendResponse(getLocalData(KEY_HE_DATA));
			break;
        	case "loadContents":
        		loadContents(sender.tab, request.list);
          	sendResponse && sendResponse();
          	break;
          case "createPage":
          	request = request || {};
			//fetch new data
			chrome.tabs.create({url:request.url, active:request.active});
          	break;
          case "removePage":
          	removePage(sender.tab);
          	break;
    }
});

//send message to content.js or extension pages
function sendMessage(data) {
	data = data || {};
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
	    chrome.tabs.sendMessage(tabs[0].id, data);
 	 });
}

function loadContents(tab, list){
	//clone
	list = list ? list.slice(0) : [];
	loadNext();
	//
	function loadNext(){
		var name = list.shift();
		if(name){
			injectContent(tab, name, null, arguments.callee);
		}else{
			sendMessage({type:"onLoadContentComplete"});
		}
	}
}

function injectContent(tab, name, type, callback){
	type = type || "js";
	if(tab && name){
		var nameRegex = /\w+\.[a-z]{2,8}$/i;
		//whether contains postfix,such as '.js'
		if(!nameRegex.test(name)){
			name += "." + type;
		}
		if(type == "js"){
			chrome.tabs.executeScript(tab.id, {file:name}, callback);
		}else if(type == "css"){
			chrome.tabs.insertCSS(tab.id, {file:name}, callback);
		}
	}
}

function removePage(tab){
	//end
	if(m_data.isWorking){
		m_data.isWorking = false;
		m_pauseCurrentTime = false;
		setLocalData(m_data, KEY_HE_DATA);
		setDynamicBadge("");
		//remove
		chrome.tabs.remove(tab.id);
		//
		fetchLeaveData();
		sendMessage({type:"onGetLeaveDataComplete"});
	}
}

function setBadge(request, sendResponse){
	m_pauseCurrentTime = true;
	setDynamicBadge(request.text, request.color);
	clearTimeout(m_hSetBadgeText);
	m_hSetBadgeText = setTimeout(function(){
		m_pauseCurrentTime = false;
	}, request.time || 1000);
}

function setDynamicBadge(str, color){
	// trace("setDynamicBadge", str);
	str = str || "";
	var total = 5;
	var i = 0;
	clearInterval(m_hBadge);
	if(str.length > total){
		str = '     ' + str;
		str = str + '     ';
		m_hBadge = setInterval(function(){
			chrome.browserAction.setBadgeText({text:str.substr(i, total)});
			i++;
			if(i >= (str.length - total - 1)){
				i = 0;
			}
		}, 150);
	}else{
		chrome.browserAction.setBadgeText({text:str});
	}
	if(color){
		chrome.browserAction.setBadgeBackgroundColor({color:color});
	}
}

function fetchLeaveData(){
	trace("fetchLeaveData", m_data);
	//start
	if(m_data.uniqueId){
		if(!isTheLatestData()){
			getCurrentMonthData();
			m_data.currentDate = getToday();
		}
	}else{
		if(!m_data.isWorking){
			m_data.isWorking = true;
			m_pauseCurrentTime = true;
			setLocalData(m_data, KEY_HE_DATA);
			setDynamicBadge("fetching data", "#9fc929");
			//fetch new data
			chrome.tabs.create({url:URL_GET_UNIQUE_ID, active:false});
		}
	}
}

function getCurrentMonthData(callback){
	$.ajax({
        url: "http://leave.happyelements.net/api/api.php?action=get_multi_days&unique_id=" + m_data.uniqueId + "&ym=" + getMonth() + "&app_key=nuew84s3&app_name=chrome",
        type: "GET",
        dataType: "json"
        }).done(function (data) {
		if(data && data.result){
			m_data.leaves = data.result;
			setLocalData(m_data, KEY_HE_DATA);
			callback && callback();
		}
     });
}

function findSomedayData(date, list){
	return _.find(list, function(data){return data.date == date;});
}

function isTheLatestDate(){
	return (m_data.currentDate == getToday());
}

function isTheLatestData(){
	var obj = findSomedayData(getToday(), m_data.leaves) || {};
	return isTheLatestDate() && Boolean(obj.first);
}

function getPastTime(){
	var todayData = findSomedayData(getToday(), m_data.leaves);
	var time = (new Date()).getTime() - (new Date(todayData && todayData.first)).getTime();
	return isTheLatestData() ? time : 0;
}

function checkCurrentTime(){
	var current = (new Date()).getTime();
	var latest = m_data.latestTime || current;
	var pastHours = (new Date(getPastTime())).getUTCHours();
	//
	//pause current time
	if(!m_pauseCurrentTime && (pastHours > 0)){
		setDynamicBadge(pastHours + "h", "#FFA500");
	}
	//hour interval
	if((current - latest) > (WORK_HOUR_INTERVAL * 60 * 60 * 1000)){
		setBadge({text:WORK_HOUR_INTERVAL + "h over", color:"#DC143C", time:0.5 * 60 * 1000});
		m_data.latestTime = current;
		setLocalData(m_data, KEY_HE_DATA);
	}
}

function checkGettingOffWork(){
	var pastTime = getPastTime();
	var totalTime = DUTY_HOURS * 60 * 60 * 1000;
	// totalTime = 3.2 * 60 * 60 * 1000;
	m_leftTime = (totalTime >= pastTime) ? (totalTime - pastTime) : 0;
	sendMessage({type:"onCheckOffWork", 
					 pastTime:pastTime, 
					 totalTime:totalTime, 
					 leftTime:m_leftTime, 
					 getOffWork:m_isGettingOffWork});
	//
	if((pastTime > 0) && (m_leftTime == 0) && (!m_isGettingOffWork)){
		m_isGettingOffWork = true;
		setBadge({text:"getting off work!", color:"#008000", time:1 * 60 * 1000});
	}
}

function timeRender(){
	checkCurrentTime();
	checkGettingOffWork();
}

function checkNewData(){
	//need to fetch data
	if(!isTheLatestData()){
		fetchLeaveData();
	}
}

function init(){
	//update today's time
	if(!isTheLatestDate()){
		m_data.latestTime = (new Date()).getTime();
		setLocalData(m_data, KEY_HE_DATA);
	}
	fetchLeaveData();
	timeRender();
	setInterval(checkNewData, 5 * 60 * 1000);
	setInterval(timeRender, 1 * 1000);
}

init();

}).call(this, window);